<?php

class DataBase extends MySQLi{

    private $link;
    private $result;
    private $sql;
    private $lastError;
    private $resultSize;
    private static $connection;
    private static $sqlQueries;
    private static $totalQueries;
    const DB_NAME = 'ffcatalunya';
    const DB_USER = 'baseweb';
    const DB_PSW = 'ACP6SMyKbVyFrEMt';
    const DB_HOST = '46.105.76.229';
    
    public static function conectar(){
        if (is_null(self::$connection)) {
            self::$connection = new DataBase();
        }
        return self::$connection;
    }

    private function __construct(){
        $this->link = parent::__construct(self::DB_HOST, self::DB_USER, self::DB_PSW, self::DB_NAME);
        if($this->connect_errno == 0){
            self::$totalQueries = 0;
            self::$sqlQueries = array();
        }
        else {
            echo 'Error en la conexion: '.$this->connect_error;
        }
    }

    private function execute(){
        if(!($this->result = $this->query($this->sql))){
            $this->lastError = $this->error;
            return false;
        }
        self::$sqlQueries[] = $this->sql;
        self::$totalQueries++;
        $this->resultSize = $this->result->num_rows;
        return true;
    }

    public function alter(){
        if(!($this->result = $this->query($this->sql))){
            $this->lastError = $this->error;
            return false;
        }
        self::$sqlQueries[] = $this->sql;
        return true;
    }

    public function loadObjectList(){
        if (!$this->execute()){
            return null;
        }
        $resultSet = array();
        while ($objectRow = $this->result->fetch_object()){
            $resultSet[] = $objectRow;
        }
        $this->result->close();
        return $resultSet;  
    }
    
    public function loadObject(){
        if ($this->execute()){
            if ($object = $this->result->fetch_object()){
                $this->result->close();
                return $object;
            }
            else return null;
        }
        else return false;
    }
    
    public function setQuery($sql){
        if(empty($sql)){
            return false;
        }
        $this->sql = $sql;
        return true;
    }

    public function getTotalQueries(){
        return self::$totalQueries;
    }
    
    public function getSQLQueries(){
        return self::$sqlQueries;
    }
    
    public function getError(){
        return $this->lastError;
    }
    
    public function getLastID(){
        return $this->insert_id;
    }
    function __destruct(){
        $this->close();
    }
}

?>